﻿// --------------------------------------------------------------------------------------
// <copyright file="AppContentTypes.cs" company="NGroup">
// Copyright (c) NGroup. All rights reserved.
// </copyright>
// --------------------------------------------------------------------------------------
// <history>
//     <change who="Bui Thanh Nam" date="2014.01.04">Create</change>
// </history>
// --------------------------------------------------------------------------------------

namespace NGroup.VTL.WebCore
{
    using System;
    using System.Collections.Generic;
    using System.Configuration;
    using System.Data;
    using System.Data.SqlClient;
    using NGroup.VTL.Core.Utilities;
    using System.Web.Mvc;
    using Newtonsoft.Json;

    public class AppContentTypes
    {
        static AppContentTypes()
        {
            UpdateAllFingers();
        }

        private static List<GenericTypeItem> appContentTypes;

        private static string productSelectListItemsJson;

        private static List<SelectListItem> level0ProductSelectListItems;

        private static readonly object lockPad = new object();

        private static bool expiredData;

        public static List<GenericTypeItem> All
        {
            get
            {
                return appContentTypes;
            }
        }

        public static string ProductSelectListItemsJson
        {
            get
            {
                return productSelectListItemsJson;
            }
        }

        public static List<SelectListItem> Level0ProductSelectListItems
        {
            get
            {
                return level0ProductSelectListItems;
            }
        }

        public static void SignalExpired(bool isExpired)
        {
            expiredData = isExpired;

            if (expiredData)
            {
                lock (lockPad)
                {
                    if (expiredData)
                    {
                        UpdateAllFingers();
                        expiredData = false;
                    }
                }
            }
        }

        private static void UpdateAllFingers()
        {
            appContentTypes = GetAllContentTypesConfigurations();
            productSelectListItemsJson = BuildProductJson();
            level0ProductSelectListItems = UpdateLevel0ProductSelectListItems();
        }

        private static string BuildProductJson()
        {
            Dictionary<string, List<SelectListItem>> productJson = new Dictionary<string, List<SelectListItem>>();

            var level0ListItems = All.FindAll(item => (!item.SupTypeID.HasValue || item.SupTypeID.Value == 0) && (item.CanEdit.HasValue == false || item.CanEdit.Value == true));

            var level1ListItems = All.FindAll(item => item.SupTypeID.HasValue == true && (item.CanEdit.HasValue == false || item.CanEdit.Value == true));

            foreach (var item in level0ListItems)
            {
                var subItems = level1ListItems.FindAll(e => e.SupTypeID == item.TypeID);

                var selectListItem = new List<SelectListItem>();

                foreach (var e in subItems)
                {
                    selectListItem.Add(new SelectListItem() { Text = e.Description, Value = e.TypeID.Value.ToString() });
                }

                productJson.Add(item.TypeID.Value.ToString(), selectListItem);
            }

            string json = JsonConvert.SerializeObject(productJson);
            return json;
        }

        private static List<SelectListItem> UpdateLevel0ProductSelectListItems()
        {
            var level0ListItems = All.FindAll(item => (!item.SupTypeID.HasValue || item.SupTypeID.Value == 0) && (item.CanEdit.HasValue == false || item.CanEdit.Value == true));
            var selectListItemsL0 = new List<SelectListItem>();
            selectListItemsL0.Add(new SelectListItem() { Text = "- Loại sản phẩm -", Value = " ", Selected = true });

            foreach (var item in level0ListItems)
            {
                selectListItemsL0.Add(new SelectListItem() { Text = item.Description, Value = item.TypeID.Value.ToString() });
            }

            return selectListItemsL0;
        }

        private static List<GenericTypeItem> GetAllContentTypesConfigurations()
        {
            string spName = "GetAllGenericTypes";
            DataSet resultDS = null;

            List<GenericTypeItem> genericTypeItemList = null;

            using (var conn = GetConnectionString())
            {
                conn.Open();

                SqlCommand command = new SqlCommand(spName, conn);
                command.CommandType = CommandType.StoredProcedure;
                resultDS = ExecuteDataset(command);
            }

            if (resultDS != null && resultDS.Tables.Count > 0)
            {
                DataTable resultTable = resultDS.Tables[0];

                genericTypeItemList = ConverDataTableToGenericTypeItemList(resultTable);

                expiredData = false;
            }

            return genericTypeItemList;
        }

        private static List<GenericTypeItem> ConverDataTableToGenericTypeItemList(DataTable data)
        {
            List<GenericTypeItem> genericTypeItemList = null;

            if (data != null)
            {
                genericTypeItemList = new List<GenericTypeItem>();

                foreach (DataRow dr in data.Rows)
                {
                    GenericTypeItem model = new GenericTypeItem();

                    model.CanEdit = SqlUtil<bool?>.GetValue(dr, "CanEdit");
                    model.CreatedAt = SqlUtil<DateTime?>.GetValue(dr, "CreatedAt");
                    model.CreatedBy = SqlUtil<string>.GetValue(dr, "CreatedBy");
                    model.Description = SqlUtil<string>.GetValue(dr, "Descriptions");
                    model.Description_En = SqlUtil<string>.GetValue(dr, "Descriptions_En");
                    model.IsActive = SqlUtil<bool?>.GetValue(dr, "IsActive");
                    model.LastUpdatedAt = SqlUtil<DateTime?>.GetValue(dr, "LastUpdatedAt");
                    model.LastUpdatedBy = SqlUtil<string>.GetValue(dr, "LastUpdatedBy");
                    model.SupTypeID = SqlUtil<int?>.GetValue(dr, "SupTypeID");
                    model.TypeID = SqlUtil<int>.GetValue(dr, "ID");
                    model.UniqueString = SqlUtil<string>.GetValue(dr, "UniqueString");
                    model.MetaDescription = SqlUtil<string>.GetValue(dr, "MetaDescription");
                    model.MetaDescription_En = SqlUtil<string>.GetValue(dr, "MetaDescription_En");
                    model.MetaKeyword = SqlUtil<string>.GetValue(dr, "MetaKeyword");
                    model.MetaKeyword_En = SqlUtil<string>.GetValue(dr, "MetaKeyword_En");

                    genericTypeItemList.Add(model);
                }
            }

            return genericTypeItemList;
        }

        private static SqlConnection GetConnectionString()
        {
            string connectionString = string.Empty;

            var settingConn = ConfigurationManager.ConnectionStrings["VTL.DB"];

            if (settingConn != null)
            {
                connectionString = settingConn.ConnectionString;
            }

            SqlConnection sqlConnection = new SqlConnection(connectionString);

            return sqlConnection;
        }

        private static DataSet ExecuteDataset(SqlCommand command)
        {
            DataSet resultDS = new DataSet();

            using (SqlDataAdapter dataAdapter = new SqlDataAdapter())
            {
                dataAdapter.SelectCommand = command;
                dataAdapter.Fill(resultDS);
            }

            return resultDS;
        }
    }
}
